/**
 * Load the APIs and run sendQuery when the load is complete
 */
var gadgetHelper = null;
_IG_RegisterOnloadHandler(loadVisualizationAPI);

var tps = new Array();

function loadVisualizationAPI()
{
    google.load("visualization", "1");
    google.setOnLoadCallback(sendQuery);
}

function Tp(name)
{
    this.name = name;
    this.events = new Array();

    this.entrega = null;
    this.entregaColor = null;
}

function TpEvent(author, practice, action, value)
{
    this.author = author;
    this.practice = practice;
    this.action = action;
    this.value = value;
}

/**
 * Create a query (shaped by the Gadget's user preferences), then
 * send it to the spreadsheet data source. Also give the name of a
 * function ("handleQueryResponse") to run once the spreadsheet data
 * is retrieved:
 */
function sendQuery()
{
    var prefs = new _IG_Prefs(); // User preferences
    gadgetHelper = new google.visualization.GadgetHelper();
    var query = gadgetHelper.createQueryFromPrefs(prefs);
    query.send(handleQueryResponse);
}

/**
 * The core logic. Process the spreadsheet data however you want.
 * In this case, we create HTML to be presented back to the user.
 * We'll use inline comments to provide a step-by-step description
 * of what we're doing:
 */
function handleQueryResponse(response)
{

    /**
     * Use the visualization GadgetHelper class to handle errors
     */
    if (!gadgetHelper.validateResponse(response)) {
        return; // Default error handling was done, just leave.
    }

    /**
     * GET THE DATA FROM THE SPREADSHEET - sorry to scream in caps, but
     * this is a key step
     */
    var prefs = new _IG_Prefs(); // User preferences
    var alumno = prefs.getString("_alumno");

    var data = response.getDataTable();

    var html = []; // start the HTML output string

    html.push('<span style="color:blue; font-size:16pt; font-weight:bold;">');
    html.push(alumno + ':');
    html.push('</span><p>');

    var events = [];

    /**
     * Process all Rows in the specified range
     */
    for (var row = 0; row < data.getNumberOfRows(); row++)
    {
        var formattedAuthor = data.getFormattedValue(row, 1);
        formattedAuthor = escapeHtml(formattedAuthor);

        var formattedPractice = data.getFormattedValue(row, 2);
        formattedPractice = escapeHtml(formattedPractice);

        var formattedAction = data.getFormattedValue(row, 3);
        formattedAction = escapeHtml(formattedAction);

        var formattedValue = data.getFormattedValue(row, 4);
        formattedValue = escapeHtml(formattedValue);

        var event = new TpEvent(formattedAuthor, formattedPractice, formattedAction, formattedValue);

        if (event.author == alumno) {
            var tp = getOrCreateTpForEvent(event);
            tp.events.push(event);
        }
    }

    tps.reverse();

    for(var i=0; i < tps.length; i++) {
            printTp(html, tps[i]);
    }

    html.push(" TOTAL EVENTS FROM AUTHOR: " + events.length);

    /**
     * Set the generated html into the container div.
     */
    var tableDiv = _gel('tablediv');
    tableDiv.innerHTML = html.join('');
    tableDiv.style.width = document.body.clientWidth + 'px';
    tableDiv.style.height = document.body.clientHeight + 'px';
}

function printTp(html, tp)
{
    /**
     * Build the practices field for printing!
     */
    buildTp(tp);
    html.push('<span style="color:blue; font-size:14pt; font-weight:bold;">');
    html.push(tp.name + "<p>");
    html.push(tp.events.length + "<p>");
    html.push('</span><p>');
    html.push('<span style="color:'+ tp.entregaColor +'; font-size:14pt; font-weight:bold;">');
    html.push(tp.entrega + "<p>");
    html.push('</span><p>');
}

function buildTp(tp)
{
    buildEntrega(tp);
//    buildNota(tp);
//    buildComments();
}

function buildEntrega(tp)
{
    for(var i=0; i < tp.events.length; i++)
    {
        var myEvent = tp.events[i]; 

        alert(myEvent.author + " / " + myEvent.practice + " / " + myEvent.action + " / " + myEvent.value);

        var actionId = getActionId(myEvent);

        if(actionId == "0") {
            alert("Action 0!");
            tp.entrega = "No entregado!";
            tp.entregaColor = "red";
            return;
        }

        if(actionId == "1") {
            alert("Action 1!");
            tp.entrega = "A tiempo " + event.value;
            tp.entregaColor = "green";
            return;
        }

        if(actionId == "2") {
            alert("Action 2!");
            tp.entrega = "Tarde " + event.value;
            tp.entregaColor = "yellow";
            return;
        }

        tp.entrega = "Error!";
    }
}

function getActionId(event)
{
    if(event == null || event == undefined
            || event.action == null || event.action == undefined) {
        alert("Error fetching actionId for event: " + event)
        return -1;
    }

    return event.action.charAt(0);
}

function getOrCreateTpForEvent(event)
{
    var tp = getTpForEvent(event);

    if(tp == null) {
        tp = new Tp(event.practice);
        tps.push(tp);
    }

    return tp;
}

function getTpForEvent(event)
{
    for(var i=0; i < tps.length; i++) {
        if(tps[i].name == event.practice) {
            return tps[i];
        }
    }

    return null;
}

/**
 * Define any supporting code you need
 * (like this handy function to escape special characters for html output):
 */
function escapeHtml(text)
{
    if (text == null) {
        return '';
    }
    return _hesc(text);
}